package com.e9where.canpoint.customrecycler.recycler.adapter;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

import com.e9where.canpoint.customrecycler.recycler.viewhold.CustomViewHold;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/12/1.
 */

public class CustomAdapter extends RecyclerView.Adapter{
    //头部类型开始端口 最小的
    private final int HEAD_POSITION=Integer.MIN_VALUE;
    //尾部类型开始端口
    private final int FOOT_POSITION=Integer.MIN_VALUE/2;
    //头部item的集合
    private List<View> headView=new ArrayList<>();
    //中间item的适配
    private RecyclerView.Adapter itemAdapter;
    //尾部item的集合
    private List<View> footView=new ArrayList<>();
    //头部长度
    public int getHeadSize() {
        return headView.size();
    }
    //尾部长度
    public int getFootSize() {
        return footView.size();
    }


    public CustomAdapter(RecyclerView.Adapter adapter) {
        this.itemAdapter = adapter;
        //嵌套adapter必须使用这个进行一个adapter注册
        itemAdapter.registerAdapterDataObserver(mDataObserver);
        //这个是解除注册
//        itemAdapter.unregisterAdapterDataObserver(mDataObserver);
    }

    //长度
    @Override
    public int getItemCount() {
        return getHeadSize()+itemAdapter.getItemCount()+getFootSize();
    }



    //类型
    @Override
    public int getItemViewType(int position) {
        if (position<getHeadSize())
        {
            return HEAD_POSITION+position;
        }
        else if (position<getHeadSize()+itemAdapter.getItemCount())
        {
            if (itemAdapter.getItemViewType(position-getHeadSize())<0)
                throw new IllegalArgumentException("adapter's getItemViewType can't less than 0");
            return itemAdapter.getItemViewType(position-getHeadSize());
        }
        else
        {
            return FOOT_POSITION+(position-getHeadSize()-itemAdapter.getItemCount());
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType<0)
        {
            //头部
            if (viewType<FOOT_POSITION)
            {
                Log.d("H","排列"+(viewType-HEAD_POSITION));
                return new CustomViewHold(headView.get(viewType-HEAD_POSITION));
            }
            //尾部
            else
            {
                return new CustomViewHold(footView.get(viewType-FOOT_POSITION));
            }
        }
        else
        {
            return itemAdapter.onCreateViewHolder(parent,viewType);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        Log.d("H",position+"排列onBindViewHolder");
        if (holder.getItemViewType()>=0)
        {
            itemAdapter.onBindViewHolder(holder,position-getHeadSize());
        }
    }

    protected void handleLayoutIfStaggeredGridLayout(RecyclerView.ViewHolder holder, int position) {
        if (isHeader(position) || isFooter(position)) {
            StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();
            p.setFullSpan(true);
        }
    }


    //使得瀑布流头尾填充布局
    @Override
    public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
        ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams();
        if(layoutParams != null ) {
            if (layoutParams instanceof StaggeredGridLayoutManager.LayoutParams)
            {
                StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) layoutParams;
                params.setFullSpan(holder.getItemViewType()<0);
            }
        }
    }



    //添加头部和尾部有个带优化，就是当先删除后添加，（设这个item不是最后一个）。不会替换位置
    //添加头部
    public void addHead(View view) {
        if (null != view)
        {
            if (headView.contains(view))
            {
                if (headView.indexOf(view)==getHeadSize()-1)
                    return;
                headView.remove(view);
                headView.add(view);
                notifyDataSetChanged();
                return;
            }
            headView.add(view);
            notifyItemInserted(getHeadSize()-1);
        }
    }

    //删除头部
    public void removeHead(View view)
    {
        if (null!=view&&headView.contains(view))
        {
            int indexOf = headView.indexOf(view);
            headView.remove(view);
            notifyItemRemoved(indexOf);
        }
    }

    //添加尾部   *占时没有优化
    public void addFoot(View view)
    {
        if (null != view)
        {
            if (footView.contains(view))
            {
                if (footView.indexOf(view)==getHeadSize()-1)
                    return;
                footView.remove(view);
                footView.add(view);
                notifyDataSetChanged();
                return;
            }
            footView.add(view);
            notifyItemInserted(getItemCount()-1);
        }
    }

    //删除尾部
    public void removeFoot(View view)
    {
        if (null != view&&footView.contains(view))
        {
            int indexOf = footView.indexOf(view);
            footView.remove(view);
            //待优化 删除的时候如果不断在那个item滑动会出现异常（“Added View has RecyclerView as parent but view is not a real child”）
//            notifyItemRemoved(getHeadSize()+itemAdapter.getItemCount()+indexOf);
            notifyDataSetChanged();
        }
    }


     //判断当前是否是header
    public boolean isHeader(int position){
        return getHeadSize() > 0 && position <= getHeadSize() - 1;
    }

     //判断当前是否是footer
    public boolean isFooter(int position){
        int lastPosition = getItemCount() - getFootSize();
        return getFootSize() > 0 && position >= lastPosition;
    }




    //注册嵌套适配器
    private RecyclerView.AdapterDataObserver mDataObserver = new RecyclerView.AdapterDataObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            notifyDataSetChanged();
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount) {
            super.onItemRangeChanged(positionStart, itemCount);
            if (getFootSize()>0)
            {
                notifyDataSetChanged();
            }
            else
            {
                notifyItemRangeChanged(positionStart + getHeadSize(),itemCount);;
            }


        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            if (getFootSize()>0)
            {
                notifyDataSetChanged();
            }
            else
            {
                notifyItemRangeInserted(positionStart + getHeadSize(),itemCount);
            }
        }

        @Override
        public void onItemRangeRemoved(int positionStart, int itemCount) {
            super.onItemRangeRemoved(positionStart, itemCount);
            //如果存在foot就必须把foot那几个也刷新
            notifyItemRangeRemoved(positionStart + getHeadSize()-getFootSize(), itemCount);
        }

        @Override
        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
            super.onItemRangeMoved(fromPosition, toPosition, itemCount);
            notifyItemRangeChanged(fromPosition + getHeadSize()-getFootSize(), toPosition + getHeadSize() + itemCount);
        }
    };
}
